package com.example.hospital.api.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONArray;
import com.example.hospital.api.db.dao.DoctorWorkPlanDao;
import com.example.hospital.api.service.MedicalDeptWorkPlanService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MedicalDeptWorkPlanServiceImpl implements MedicalDeptWorkPlanService {
    @Resource
    private DoctorWorkPlanDao doctorWorkPlanDao;

    @Override
    public List<Map> selectWorkPlanInRange(Map param, List<String> dateList) {
        List<HashMap> list = doctorWorkPlanDao.selectWorkPlanInRange(param);

        Map<String, List<HashMap>> collect = list.stream().collect(Collectors.groupingBy(e -> groupCondition(e)));

        List<Map> result = new ArrayList<>();
        for (Map.Entry<String, List<HashMap>> entry : collect.entrySet()) {
            List<HashMap> mapList = entry.getValue();

            Map<String, Object> resultMap = new HashMap<>();
            Map<String, List<String>> dateToDoctors = new HashMap<>();
            int row = 0;
            for (HashMap map : mapList) {
                if(row==0){
                    resultMap.put("deptName", map.get("deptName"));
                    resultMap.put("deptSubId", map.get("deptSubId"));
                    resultMap.put("deptSubName", map.get("deptSubName"));
                    row++;
                }
                String date = MapUtil.getStr(map, "date");
                String doctorName = MapUtil.getStr(map, "doctorName");
                dateToDoctors.computeIfAbsent(date, e -> new ArrayList<>()).add(doctorName);
            }
            List<Map> planList = new ArrayList<>();
            for (String dateStr : dateList) {
                Map dateMap = new HashMap();
                dateMap.put("date", dateStr);
                dateMap.put("doctors", dateToDoctors.get(dateStr) == null ? new ArrayList<>() : dateToDoctors.get(dateStr));
                planList.add(dateMap);
            }
            resultMap.put("plan", planList);
            result.add(resultMap);
        }
        return result;
    }

    private String groupCondition(HashMap one) {
        String deptName = MapUtil.getStr(one, "deptName");
        int deptSlbId = MapUtil.getInt(one, "deptSubId");
        return deptName + "#$#" + deptSlbId;
    }
}
